<template>
	<view class="voice-icon-box theme-shadow">
		<text class="cuIcon-notificationfill voice-icon" @click="handlePlay"></text>
	</view>
</template>

<script setup lang="ts">
import { text2Voice } from "@/utils/common"
import { Ref, ref } from "vue"
	
const props = defineProps({
	title: {
		type: String,
		default: ""
	},
	content: {
		type: String,
		default: ""
	}
})
let innerAudioContext = null
const playing: Ref<boolean> = ref(false)
const handlePlay = () => {
	if (!innerAudioContext) {
		text2Voice(props.title + props.content)
			.then((res) => {
				innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = res.filepath;
				innerAudioContext.onPlay(() => {
					playing.value = true
				  console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
				  console.log(res.errMsg);
				  console.log(res.errCode);
				});
				innerAudioContext.onStop((res) => {
					playing.value = false
				})
				innerAudioContext.play()
			})
			.catch((err) => {
				console.log(err)
				uni.showToast({
					icon: "none",
					title: "语音加载失败"
				})
			})
	} else  {
		if (playing.value) {
			innerAudioContext.stop()
		} else {
			innerAudioContext.play()
		}
	}
}

</script>

<style lang="stylus" scoped>
	
.voice-icon-box
	position: fixed
	top: 20vh
	right 30rpx
	z-index: 99
	background: #fff
	height: 60rpx
	width: 60rpx
	border-radius: 30rpx
	padding 0 20rpx
	display: flex
	align-items: center
	justify-content: center
	.voice-icon
		color: #dfa439
</style>